package com.java.escape.springproblem.bean_post_processor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

/**
 * @ClassName DecoderManager
 * @Description TODO
 * @Author wyp
 * @Date 2023/9/18 11:04
 * @Version 1.0
 */
@Service
@Slf4j
public class DecoderManager implements BeanPostProcessor {
    private static final Map<VideoType, IDecoder> videoTypeIndex = new HashMap<>
            (VideoType.values().length);
    public static final Map<String, Long> totalTime = new HashMap<>();

    static {
        totalTime.put("totalTime", 0L);
    }

    public String decode(VideoType type, String data) {
        String result = null;
        switch (type) {
            case AVI:
                result = videoTypeIndex.get(VideoType.AVI).decode(data);
                break;
            case WMV:
                result = videoTypeIndex.get(VideoType.WMV).decode(data);
                break;
            default:
                log.info("error");
        }
        return result;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Long begin = System.currentTimeMillis();
        if (!(bean instanceof IDecoder)) {
            return bean;
        }
        IDecoder decoder = (IDecoder) bean;
        VideoType type = decoder.type();
        if (videoTypeIndex.containsKey(type)) {
            throw new IllegalStateException("重复注册!");
        }
        log.info("load Decoder {} for Video type {}", decoder.getClass(), type.getDesc());
        videoTypeIndex.put(type, decoder);
        Long end = System.currentTimeMillis();
        Long spendTime = end - begin;
        System.out.println(spendTime);
        Long totalTime1 = totalTime.get("totalTime");
        Long merge = totalTime.merge("totalTime", totalTime1, (key,value)->value+totalTime1);
        System.out.println("merge" + merge);
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (!(bean instanceof IDecoder)) {
            return bean;
        }
        log.info("BeanPostProcessor after init: {}", bean.getClass());
        return null;
    }
}
